<?php

/*
  Plugin Name: HTML5 AV Manager for Wordpress
  Plugin URI: http://cj-jackson.com/
  Description: A video manager with a Modal-View-Controller and video uploader.
  Version: 0.2.8
  Author: Christopher John Jackson
  Author URI: http://cj-jackson.com/
  License: MIT/X11
 */

/**
 * Copyright (c) 2011 Christopher John Jackson
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
$noPDO = false;

if (!class_exists("PDO")) {
    $noPDO = true;
} elseif (!in_array('mysql', PDO::getAvailableDrivers())) {
    $noPDO = true;
}

if ($noPDO) {
    deactivate_plugins(basename(__FILE__));
    wp_die("HTML5 AV Manager for Wordpress failed to activate, because your
        server does not have PDO or PDO_MYSQL installed, make sure you have PDO
        and PDO_MYSQL installed or ask your host to install it for you,
        Thank you!");
}

if (!(is_writable(WP_CONTENT_DIR) && is_readable(WP_CONTENT_DIR))) {
    deactivate_plugins(basename(__FILE__));
    $wpcontent = WP_CONTENT_DIR;
    wp_die("HTML5 AV Manager for Wordpress has detected that '$wpcontent' not
            writable or readable, therefore deactivated itself, make sure that
            directory is chmoded to '755', thank you!");
}

if (!function_exists('json_encode')) {
    deactivate_plugins(basename(__FILE__));
    wp_die("HTML5 AV Manager for Wordpress has detected that your server
        installation of PHP does not have 'json' module installed, therefore
        deactivated itself!");
}

require_once 'lib/time.php';
require_once 'lib/html5av_dbal.php';

class html5av_manager {

    static private $DIR;
    static private $URL;
    static private $UPLOAD_DIR;
    static private $UPLOAD_URL;
    static private $param;
    static private $audio_type;
    static private $video_type;
    static private $audio_ext;
    static private $video_ext;
    static private $position;
    static private $video_view;
    static private $audio_view;
    static private $video_flash_compatible;
    static private $audio_flash_compatible;
    static private $track_kind;
    static private $view_path;
    static private $xml_mode;

    // Initialization
    static public function init() {
        $pluginfolder = dirname(__FILE__);
        $pluginfolder = str_replace('\\', '/', $pluginfolder);
        $pluginfolder = explode('/', $pluginfolder);
        $pluginfolder = end($pluginfolder);
        // Set up paths
        self::$DIR = WP_PLUGIN_DIR . '/' . $pluginfolder;
        self::$URL = WP_PLUGIN_URL . '/' . $pluginfolder;
        self::$UPLOAD_DIR = WP_CONTENT_DIR . '/videoaudio';
        self::$UPLOAD_URL = WP_CONTENT_URL . '/videoaudio';
        self::$view_path = WP_CONTENT_DIR . '/videoaudio/views';

        $uploadify_setting_file = self::$DIR . '/lib/uploadify/' . $_SERVER['HTTP_HOST'] . '.json';
        if (!file_exists($uploadify_setting_file)) {
            $uploadify_json['dir'] = self::$UPLOAD_DIR;
            $uploadify_json = json_encode($uploadify_json);
            chmod(dirname($uploadify_setting_file), 0755);
            file_put_contents($uploadify_setting_file, $uploadify_json);
        }

        // Set up param
        self::$param = self::cleanParam();

        self::$audio_type = array(
            'AAC/MP4 (Low-Complexity)' => 'audio/aac; codecs="mp4a.40.2"',
            'Ogg (Vorbis)' => 'video/ogg; codecs="vorbis"',
            'WebM (Vorbis)' => 'audio/webm; codecs="vorbis"',
            'MP3' => 'audio/mpeg'
        );

        self::$audio_ext = array(
            '*.aac', '*.mp4', '*.m4a', '*.ogg', '*.oga', '*.webm', '*.mp3'
        );

        self::$video_type = array(
            'MP4 (H.264 Baseline & AAC-LC)' => 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
            'MP4 (H.264 Extended & AAC-LC)' => 'video/mp4; codecs="avc1.58A01E, mp4a.40.2"',
            'MP4 (H.264 Main & AAC-LC)' => 'video/mp4; codecs="avc1.4D401E, mp4a.40.2"',
            'MP4 (H.264 High & AAC-LC)' => 'video/mp4; codecs="avc1.64001E, mp4a.40.2"',
            'WebM (VP8 & Vorbis)' => 'video/webm; codecs="vp8, vorbis"',
            'Ogg (Theora & Vorbis)' => 'video/ogg; codecs="theora, vorbis"'
        );

        self::$video_ext = array(
            '*.mp4', '*.m4v', '*.webm', '*.ogg', '*.ogv'
        );

        self::$position = array(
            'top', 'bottom', 'manual'
        );

        self::$audio_flash_compatible = array(
            'audio/aac; codecs="mp4a.40.2"',
            'audio/mpeg'
        );

        self::$video_flash_compatible = array(
            'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
            'video/mp4; codecs="avc1.58A01E, mp4a.40.2"',
            'video/mp4; codecs="avc1.4D401E, mp4a.40.2"',
            'video/mp4; codecs="avc1.64001E, mp4a.40.2"'
        );

        self::$track_kind = array(
            'subtitles',
            'captions',
            'description',
            'chapters',
            'metadata'
        );

        self::$xml_mode = false;

        if (!file_exists(self::$view_path . '/video-default.php')) {
            @mkdir(self::$view_path, 0755, true);
            copy(self::$DIR . '/view/videoaudio/setting.php', self::$view_path . '/setting.php');
            copy(self::$DIR . '/view/videoaudio/video-default.php', self::$view_path . '/video-default.php');
            copy(self::$DIR . '/view/videoaudio/video-xml.php', self::$view_path . '/video-xml.php');
            copy(self::$DIR . '/view/videoaudio/audio-default.php', self::$view_path . '/audio-default.php');
            copy(self::$DIR . '/view/videoaudio/audio-xml.php', self::$view_path . '/audio-xml.php');
        }

        if (file_exists(self::$view_path . '/video-default.php')) {
            include self::$view_path . '/setting.php';
            $viewsDir = self::$view_path . '/';
        } else {
            include self::$DIR . '/view/videoaudio/setting.php';
            $viewsDir = self::$DIR . '/view/videoaudio/';
        }

        $audioViews = glob($viewsDir . "audio-*.php");

        foreach ($audioViews as $view) {
            $view = basename($view);
            $view = substr($view, 6, -4);
            if ($view != 'xml') {
                self::$audio_view[] = $view;
            }
            unset($view);
        }

        $videoViews = glob($viewsDir . "video-*.php");

        foreach ($videoViews as $view) {
            $view = basename($view);
            $view = substr($view, 6, -4);
            if ($view != 'xml') {
                self::$video_view[] = $view;
            }
            unset($view);
        }

        $db = new html5av_dbal();
        $db->setUpTables();
        $db->updateTables();
        unset($db);
    }

    static private function cleanParam() {
        $param = array_merge($_POST, $_GET);

        $param = is_array($param) ?
                array_map('stripslashes_deep', $param) :
                stripslashes($param);

        return $param;
    }

    static public function getDir() {
        return self::$DIR;
    }

    static public function getUrl() {
        return self::$URL;
    }

    static public function getUploadDir() {
        return self::$UPLOAD_DIR;
    }

    static public function getUploadUrl() {
        return self::$UPLOAD_URL;
    }

    static public function getParam() {
        return self::$param;
    }

    static public function getApiURL() {
        return self::getUrl() . '/api.php';
    }

    static public function getAudioType() {
        return self::$audio_type;
    }

    static public function getVideoType() {
        return self::$video_type;
    }

    static public function getAudioExt() {
        return self::$audio_ext;
    }

    static public function getVideoExt() {
        return self::$video_ext;
    }

    static public function getPositions() {
        return self::$position;
    }

    static public function getVideoViews() {
        return self::$video_view;
    }

    static public function getAudioViews() {
        return self::$audio_view;
    }

    static public function getVideoFlash() {
        return self::$video_flash_compatible;
    }

    static public function getAudioFlash() {
        return self::$audio_flash_compatible;
    }

    static public function getTrackKinds() {
        return self::$track_kind;
    }

    static public function getViewPath() {
        return self::$view_path;
    }

    static public function getXmlMode() {
        return self::$xml_mode;
    }

    static public function setXmlMode() {
        self::$xml_mode = true;
    }

    static public function scripts() {
        if (is_admin()) {
            wp_enqueue_script('jquery');
            wp_enqueue_script('jquery-ui-core');
            wp_enqueue_script('jquery-ui-dialog');
            wp_enqueue_script('jquery-ui-sortable');
            wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css');
            wp_enqueue_script('swfobject');
            wp_enqueue_script('html5av_manager_uploadify', self::getUrl() . '/lib/uploadify/jquery.uploadify.js');
            wp_enqueue_style('html5av_manager_uploadify', self::getUrl() . '/lib/uploadify/uploadify.css');
        }
    }

    static public function activate() {
        add_option('html5av_manager_dbrev', '0');
        add_option('html5av_manager_position', 'top');
        add_option('html5av_manager_video_view', 'default');
        add_option('html5av_manager_audio_view', 'default');
    }

    static public function slug($str) {
        $str = strtolower(trim($str));
        $str = preg_replace('/[^a-z0-9-]/', '-', $str);
        $str = preg_replace('/-+/', "-", $str);
        return $str;
    }

    static public function menu() {
        add_menu_page('HTML5 Video & Audio Manager', 'HTML5 AV', 'edit_posts', 'html5av.php', array('html5av_manager', 'videoAudioManagerPanel'));
        add_submenu_page('html5av.php', 'HTML5 Video & Audio Manager', 'HTML5 Video & Audio Manager', 'edit_posts', 'html5av.php', array('html5av_manager', 'videoAudioManagerPanel'));
        add_submenu_page('html5av.php', 'Add Video', 'Add Video', 'edit_posts', 'html5av-add-video.php', array('html5av_manager', 'videoAddPanel'));
        add_submenu_page('html5av.php', 'Add Audio', 'Add Audio', 'edit_posts', 'html5av-add-audio.php', array('html5av_manager', 'audioAddPanel'));
        add_submenu_page('html5av.php', 'View Editor', 'View Editor', 'manage_options', 'html5av-view-editor.php', array('html5av_manager', 'viewEditorPanel'));
        add_submenu_page('html5av.php', 'Settings', 'Settings', 'manage_options', 'html5av-setting.php', array('html5av_manager', 'settingsPanel'));
        $settings = array(
            'html5av_manager_position',
            'html5av_manager_video_view',
            'html5av_manager_audio_view'
        );
        foreach ($settings as $setting) {
            register_setting('html5av_manager_settting', $setting);
        }
        unset($settings);

        if (function_exists('add_meta_box')) {
            add_meta_box('html5av_manager_widget', 'HTML5 AV Manager', array('html5av_manager', 'widget'), 'post', 'advanced');
            add_meta_box('html5av_manager_widget', 'HTML5 AV Manager', array('html5av_manager', 'widget'), 'page', 'advanced');
            add_meta_box('html5av_manager_widget', 'HTML5 AV Manager', array('html5av_manager', 'widget'), 'custom_post_type', 'advanced');
        }
    }

    static public function videoAudioManagerPanel() {
        include 'view/admin/video-audio-manager-panel.php';
        include 'view/admin/message.php';
    }

    static public function videoAddPanel() {
        $tempVideoViews = self::getVideoViews();
        $videoViews = array();
        foreach ($tempVideoViews as $tempVideoView) {
            $videoViews[$tempVideoView] = '';
        }
        unset($tempVideoView);
        unset($tempVideoViews);
        include 'view/admin/video-add-panel.php';
        include 'view/admin/message.php';
    }

    static public function audioAddPanel() {
        $tempAudioViews = self::getAudioViews();
        $audioViews = array();
        foreach ($tempAudioViews as $tempAudioView) {
            $audioViews[$tempAudioView] = '';
        }
        unset($tempAudioView);
        unset($tempAudioViews);
        include 'view/admin/audio-add-panel.php';
        include 'view/admin/message.php';
    }

    static public function settingsPanel() {
        $tempPositions = self::getPositions();
        $positions = array();
        foreach ($tempPositions as $position) {
            if ($position == trim(get_option('html5av_manager_position'))) {
                $positions[$position] = 'selected';
            } else {
                $positions[$position] = '';
            }
        }
        unset($position);
        unset($tempPositions);
        $tempVideoViews = self::getVideoViews();
        $videoViews = array();
        foreach ($tempVideoViews as $tempVideoView) {
            if ($tempVideoView == trim(get_option('html5av_manager_video_view'))) {
                $videoViews[$tempVideoView] = 'selected';
            } else {
                $videoViews[$tempVideoView] = '';
            }
        }
        unset($tempVideoView);
        unset($tempVideoViews);
        $tempAudioViews = self::getAudioViews();
        $audioViews = array();
        foreach ($tempAudioViews as $tempAudioView) {
            if ($tempAudioView == trim(get_option('html5av_manager_audio_view'))) {
                $audioViews[$tempAudioView] = 'selected';
            } else {
                $audioViews[$tempAudioView] = '';
            }
        }
        unset($tempAudioView);
        unset($tempAudioViews);
        $file_setting = "";
        if (file_exists(self::getViewPath() . '/setting.php')) {
            $file_setting = file_get_contents(self::getViewPath() . '/setting.php');
        }
        include 'view/admin/settings-panel.php';
        include 'view/admin/message.php';
    }

    static public function viewEditorPanel() {
        include 'view/admin/view-editor.php';
    }

    static public function checkVideoFlash($type) {
        $type = trim($type);
        $videoFlashes = self::getVideoFlash();
        foreach ($videoFlashes as $videoFlash) {
            if ($type == $videoFlash) {
                return true;
            }
        }
        return false;
    }

    static public function checkAudioFlash($type) {
        $type = trim($type);
        $audioFlashes = self::getAudioFlash();
        foreach ($audioFlashes as $audioFlash) {
            if ($type == $audioFlash) {
                return true;
            }
        }
        return false;
    }

    static public function mediaEditor() {
        $id = self::$param['avid'];
        $audioVideo = html5av_audio_video_table::getByID($id);
        $type = trim($audioVideo->getType());
        if ($type == 'video') {
            self::videoEditor($audioVideo);
        } else {
            self::audioEditor($audioVideo);
        }
    }

    static private function videoEditor($video) {
        $id = $video->getID();
        $title = htmlspecialchars($video->getTitle());
        $alt = htmlspecialchars($video->getAlt());
        $type = 'video';
        $width = $video->getWidth();
        $height = $video->getHeight();
        $view = $video->getView();

        $tempVideoViews = self::getVideoViews();
        $videoViews = array();
        foreach ($tempVideoViews as $tempVideoView) {
            if ($tempVideoView == trim($view)) {
                $videoViews[$tempVideoView] = 'selected';
            } else {
                $videoViews[$tempVideoView] = '';
            }
        }
        unset($tempVideoView);
        unset($tempVideoViews);

        $tempSources = $video->getSources(true);

        $codecs = self::getVideoType();
        $sources = array();
        foreach ($tempSources as $source) {
            if ($source->getExternalMode()) {
                $external = 'Yes';
            } else {
                $external = 'No';
            }
            $tempSource = array(
                'ID' => $source->getID(),
                'type' => $source->getType(),
                'src' => htmlspecialchars($source->getSrcUrl()),
                'external' => $external,
                'disabled' => $source->getDisabled()
            );

            $sources[] = $tempSource;
        }

        $tempTracks = $video->getTracks(true);

        $kinds = self::getTrackKinds();
        $tracks = array();
        foreach ($tempTracks as $track) {
            if ($track->getExternalMode()) {
                $external = 'Yes';
            } else {
                $external = 'No';
            }
            $tempTrack = array(
                'ID' => $track->getID(),
                'kind' => $track->getKind(),
                'src' => htmlspecialchars($track->getSrcUrl()),
                'external' => $external,
                'disabled' => $track->getDisabled(),
                'srclang' => $track->getSrclang(),
                'label' => $track->getLabel()
            );

            $tracks[] = $tempTrack;
        }

        include 'view/admin/video-edit-panel.php';
    }

    static private function audioEditor($audio) {
        $id = $audio->getID();
        $title = htmlspecialchars($audio->getTitle());
        $alt = htmlspecialchars($audio->getAlt());
        $type = 'audio';
        $view = $audio->getView();

        $tempAudioViews = self::getAudioViews();
        $audioViews = array();
        foreach ($tempAudioViews as $tempAudioView) {
            if ($tempAudioView == trim($view)) {
                $audioViews[$tempAudioView] = 'selected';
            } else {
                $audioViews[$tempAudioView] = '';
            }
        }
        unset($tempAudioView);
        unset($tempAudioViews);

        $tempSources = $audio->getSources(true);

        $codecs = self::getAudioType();
        $sources = array();
        foreach ($tempSources as $source) {
            if ($source->getExternalMode()) {
                $external = 'Yes';
            } else {
                $external = 'No';
            }
            $tempSource = array(
                'ID' => $source->getID(),
                'type' => $source->getType(),
                'src' => htmlspecialchars($source->getSrcUrl()),
                'external' => $external,
                'disabled' => $source->getDisabled()
            );

            $sources[] = $tempSource;
        }

        $tempTracks = $audio->getTracks(true);

        $kinds = self::getTrackKinds();
        $tracks = array();
        foreach ($tempTracks as $track) {
            if ($track->getExternalMode()) {
                $external = 'Yes';
            } else {
                $external = 'No';
            }
            $tempTrack = array(
                'ID' => $track->getID(),
                'kind' => $track->getKind(),
                'src' => htmlspecialchars($track->getSrcUrl()),
                'external' => $external,
                'disabled' => $track->getDisabled(),
                'srclang' => $track->getSrclang(),
                'label' => $track->getLabel()
            );

            $tracks[] = $tempTrack;
        }

        include 'view/admin/audio-edit-panel.php';
    }

    static public function determineType($file, $media) {
        $media = trim($media);
        if ($media == 'video') {
            return self::determineVideo($file);
        } else {
            return self::determineAudio($file);
        }
    }

    static public function determineVideo($file) {
        $type = self::getVideoType();

        $ext = strtolower(end(explode('.', $file)));

        if ($ext == 'mp4' || $ext == 'm4v') {
            return $type['MP4 (H.264 Baseline & AAC-LC)'];
        }

        if ($ext == 'webm') {
            return $type['WebM (VP8 & Vorbis)'];
        }

        return $type['Ogg (Theora & Vorbis)'];
    }

    static public function determineAudio($file) {
        $type = self::getAudioType();

        $ext = strtolower(end(explode('.', $file)));

        if ($ext == 'mp4' || $ext == 'm4a' || $ext == 'aac') {
            return $type['AAC/MP4 (Low-Complexity)'];
        }

        if ($ext == 'webm') {
            return $type['WebM (Vorbis)'];
        }

        if ($ext == 'ogg' || $ext == 'oga') {
            return $type['Ogg (Vorbis)'];
        }

        return $type['MP3'];
    }

    static public function widget() {
        global $post_ID;
        $videoAudioID = get_post_meta($post_ID, '_html5avmanager', true);

        include 'view/admin/widget.php';
    }

    static public function postSave($postID) {
        global $wpdb;

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
            return;

        // Get the correct post ID if revision.
        if ($wpdb->get_var("SELECT post_type FROM $wpdb->posts WHERE ID=$postID") == 'revision')
            $postID = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID=$postID");

        if (isset(self::$param['html5avmanagerid'])) {
            $videoAudioID = (int) trim(self::$param['html5avmanagerid']);
        } else {
            $videoAudioID = get_post_meta($postID, '_html5avmanager', true);
        }

        if (!update_post_meta($postID, '_html5avmanager', $videoAudioID))
            update_post_meta($postID, '_html5avmanager', $videoAudioID);
    }

    static public function getAVFromPost($post_id) {
        $id = (int) get_post_meta($post_id, '_html5avmanager', true);
        self::getHTML5AV($id);
    }

    static public function getHTML5AV($id, $view = false) {
        if ($id == '') {
            echo '';
            return;
        }
        $audioVideo = html5av_audio_video_table::getByID($id);
        if (!method_exists($audioVideo, 'getType')) {
            echo '';
            return;
        }
        $type = trim($audioVideo->getType());
        if ($type == 'video') {
            self::getHTML5Video($audioVideo, $view);
        } else {
            self::getHTML5Audio($audioVideo, $view);
        }
    }

    static private function getHTML5Video($video, $view) {
        if (!$view) {
            $view = $video->getView();
        }
        if (trim($view) == 'default') {
            $view = trim(get_option('html5av_manager_video_view'));
        }
        $id = $video->getID();
        $view = 'video-' . trim($view) . '.php';
        $title = htmlspecialchars($video->getTitle());
        $alt = htmlspecialchars($video->getAlt());
        $width = $video->getWidth();
        $height = $video->getHeight();
        $poster = htmlspecialchars($video->getPosterUrl());

        $tempSources = $video->getSources();
        $flashVideo = false;
        $sources = array();
        $closedLinks = array();
        $openLinks = array();
        $links = array();
        foreach ($tempSources as $tempSource) {
            if (!$flashVideo) {
                if (self::checkVideoFlash($tempSource->getType())) {
                    $flashVideo = htmlspecialchars($tempSource->getSrcUrl());
                }
            }

            $closedLink = self::closedLink($tempSource->getType(), 'video');
            if ($closedLink) {
                $closedLinks[] = array(
                    'href' => htmlspecialchars($tempSource->getSrcUrl()),
                    'name' => $closedLink
                );
            }

            $openLink = self::openLink($tempSource->getType(), 'video');
            if ($openLink) {
                $openLinks[] = array(
                    'href' => htmlspecialchars($tempSource->getSrcUrl()),
                    'name' => $openLink
                );
            }

            $source = array(
                'src' => htmlspecialchars($tempSource->getSrcUrl()),
                'type' => $tempSource->getType()
            );
            $sources[] = $source;
        }
        unset($tempSources);
        unset($tempSource);

        $links = array_merge($closedLinks, $openLinks);

        $tempTracks = $video->getTracks();
        $tracks = array();
        foreach ($tempTracks as $tempTrack) {
            $track = array(
                'src' => htmlspecialchars($tempTrack->getSrcUrl()),
                'kind' => $tempTrack->getKind(),
                'srclang' => htmlspecialchars($tempTrack->getSrclang()),
                'label' => htmlspecialchars($tempTrack->getLabel())
            );
            $tracks[] = $track;
        }
        unset($tempTracks);
        unset($tempTrack);

        if (!count($sources)) {
            echo '';
            return;
        }

        if (self::getXmlMode()) {
            include self::getViewPath() . '/video-xml.php';
        } else {
            if (file_exists(self::getViewPath() . '/' . $view)) {
                include self::getViewPath() . '/' . $view;
            } else {
                include self::getViewPath() . '/video-default.php';
            }
        }
    }

    static private function getHTML5Audio($audio, $view) {
        if (!$view) {
            $view = $audio->getView();
        }
        if (trim($view) == 'default') {
            $view = trim(get_option('html5av_manager_audio_view'));
        }
        $view = 'audio-' . trim($view) . '.php';
        $id = $audio->getID();
        $title = htmlspecialchars($audio->getTitle());
        $alt = htmlspecialchars($audio->getAlt());

        //$poster = 'http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif';
        //$width = $height = 1;

        $tempSources = $audio->getSources();
        $flashAudio = false;
        $sources = array();
        $closedLinks = array();
        $openLinks = array();
        foreach ($tempSources as $tempSource) {
            if (!$flashAudio) {
                if (self::checkAudioFlash($tempSource->getType())) {
                    $flashAudio = htmlspecialchars($tempSource->getSrcUrl());
                }
            }

            $closedLink = self::closedLink($tempSource->getType(), 'audio');
            if ($closedLink) {
                $closedLinks[] = array(
                    'href' => htmlspecialchars($tempSource->getSrcUrl()),
                    'name' => $closedLink
                );
            }

            $openLink = self::openLink($tempSource->getType(), 'audio');
            if ($openLink) {
                $openLinks[] = array(
                    'href' => htmlspecialchars($tempSource->getSrcUrl()),
                    'name' => $openLink
                );
            }

            $source = array(
                'src' => htmlspecialchars($tempSource->getSrcUrl()),
                'type' => $tempSource->getType()
            );
            $sources[] = $source;
        }
        unset($tempSources);
        unset($tempSource);

        $links = array_merge($closedLinks, $openLinks);

        $tempTracks = $audio->getTracks();
        $tracks = array();
        foreach ($tempTracks as $tempTrack) {
            $track = array(
                'src' => htmlspecialchars($tempTrack->getSrcUrl()),
                'kind' => $tempTrack->getKind(),
                'srclang' => htmlspecialchars($tempTrack->getSrclang()),
                'label' => htmlspecialchars($tempTrack->getLabel())
            );
            $tracks[] = $track;
        }
        unset($tempTracks);
        unset($tempTrack);

        if (!count($sources)) {
            echo '';
            return;
        }

        if (self::getXmlMode()) {
            include self::getViewPath() . '/audio-xml.php';
        } else {
            if (file_exists(self::getViewPath() . '/' . $view)) {
                include self::getViewPath() . '/' . $view;
            } else {
                include self::getViewPath() . '/audio-default.php';
            }
        }
    }

    static public function shortcode($atts) {
        extract(shortcode_atts(array(
                    'id' => 0,
                    'view' => false,
                        ), $atts));
        ob_start();
        self::getHTML5AV($id, $view);
        $output = ob_get_clean();
        return $output;
    }

    static public function contentFilter($content) {
        if (get_option('html5av_manager_position') != 'manual') {
            ob_start();
            self::getAVFromPost(get_the_ID());
            $output = ob_get_clean();
            if ($output != '') {
                if (get_option('html5av_manager_position') == 'top') {
                    return $output . '<br />' . $content;
                }
                if (get_option('html5av_manager_position') == 'bottom') {
                    return $content . '<br />' . $output;
                }
            }
        }
        return $content;
    }

    static private function closedLink($codec, $type) {
        if ($type == 'video') {
            $TempCodecs = html5av_manager::getVideoType();
            $codecs = array(
                $TempCodecs['MP4 (H.264 Baseline & AAC-LC)'] => 'MP4 (Baseline)',
                $TempCodecs['MP4 (H.264 Extended & AAC-LC)'] => 'MP4 (Extended)',
                $TempCodecs['MP4 (H.264 Main & AAC-LC)'] => 'MP4 (Main)',
                $TempCodecs['MP4 (H.264 High & AAC-LC)'] => 'MP4 (High)'
            );
        } else {
            $TempCodecs = html5av_manager::getAudioType();
            $codecs = array(
                $TempCodecs['AAC/MP4 (Low-Complexity)'] => 'AAC',
                $TempCodecs['MP3'] => 'MP3'
            );
        }

        if (isset($codecs[$codec])) {
            return $codecs[$codec];
        } else {
            return false;
        }
    }

    static private function openLink($codec, $type) {
        if ($type == 'video') {
            $TempCodecs = html5av_manager::getVideoType();
            $codecs = array(
                $TempCodecs['WebM (VP8 & Vorbis)'] => 'WebM',
                $TempCodecs['Ogg (Theora & Vorbis)'] => 'Ogg'
            );
        } else {
            $TempCodecs = html5av_manager::getAudioType();
            $codecs = array(
                $TempCodecs['Ogg (Vorbis)'] => 'Ogg',
                $TempCodecs['WebM (Vorbis)'] => 'WebM'
            );
        }

        if (isset($codecs[$codec])) {
            return $codecs[$codec];
        } else {
            return false;
        }
    }

}

add_action('init', array('html5av_manager', 'init'));
add_action('init', array('html5av_manager', 'scripts'));
register_activation_hook(__FILE__, array('html5av_manager', 'activate'));
add_action('admin_menu', array('html5av_manager', 'menu'));
add_action('save_post', array('html5av_manager', 'postSave'));
add_action('get_htmlav_from_post', array('html5av_manager', 'getAVFromPost'), 10, 1);
add_shortcode('html5av', array('html5av_manager', 'shortcode'));
add_filter('the_content', array('html5av_manager', 'contentFilter'));
add_action('atom_head', array('html5av_manager', 'setXmlMode'));
add_action('rss_head', array('html5av_manager', 'setXmlMode'));
add_action('rss2_head', array('html5av_manager', 'setXmlMode'));
add_action('rdf_header', array('html5av_manager', 'setXmlMode'));

require_once 'api.php';